package service

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"io/ioutil"
	e "itchat4go/enum"
	m "itchat4go/model"
	t "itchat4go/tools"
	"logs"
	"net/http"
	"net/url"
	"time"
)

/**
 * 获取所有联系人信息，组装到map中，key为用户的UserName
 * 微信API对此URL使用了Cookie验证
 * GET:https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket=dfLHy%252Fcgw%252BFM1qGhuARU6%252BDGs%252BGmWAD3jZJk6%252BfWcPs%253D&r=1504587952374&seq=0&skey=@crypt_3aaab8d5_c87634a7c5f8f579095cfdceeb8d842a
 */
func GetAllContact() (map[string]m.User, error) {
	contactMap := map[string]m.User{}

	urlMap := e.GetInitParaEnum()
	urlMap[e.PassTicket] = m.LoginM.PassTicket
	urlMap[e.R] = fmt.Sprintf("%d", time.Now().UnixNano()/1000000)
	urlMap["seq"] = "0"
	urlMap[e.SKey] = m.LoginM.BaseRequest.SKey

	/* 使用Cookie功能，Get数据 */
	u, _ := url.Parse("https://wx.qq.com")

	jar := new(m.Jar)
	jar.SetCookies(u, m.LoginM.Cookies)

	client := &http.Client{
		Jar: jar}

	resp, err := client.Get(e.GET_ALL_CONTACT_URL + t.GetURLParams(urlMap))
	if err != nil {
		return contactMap, err
	}
	defer resp.Body.Close()

	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return contactMap, err
	}

	contactList := m.ContactList{}
	err = json.Unmarshal(bodyBytes, &contactList)
	if err != nil {
		return contactMap, err
	}

	logs.Info("读取联系人数据：", string(bodyBytes[:]))

	for i := 0; i < contactList.MemberCount; i++ {
		contactMap[contactList.MemberList[i].UserName] = contactList.MemberList[i]
	}

	return contactMap, nil
}

/*
获得群的联系人
POST:https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=1506346263483
请求主体：
{

"BaseRequest":
{"Uin":2567063980,"Sid":"vMchR8ufIIYOhPm1",
"Skey":"@crypt_17353144_a2cf5f21b35849d200c31691185b8ab1",
"DeviceID":"e008631365456735"},

"Count":1,

"List":[{"UserName":"@@ca4d30308f1184f779bdcd581c00aeadf8fccbfbb498f3441e66887fd9b5afb4","EncryChatRoomId":""}]}
*/
func GetGroupContact(loginMap *m.LoginMap, userList []*m.User) (resUserList map[string]m.User, err error) {

	urlMap := e.GetInitParaEnum()
	urlMap[e.R] = fmt.Sprintf("%d", time.Now().UnixNano()/1000000)
	urlMap["type"] = "ex"

	/* 使用Cookie功能，Get数据 */
	/*u, _ := url.Parse("https://wx.qq.com")
	jar := new(m.Jar)
	jar.SetCookies(u, loginMap.Cookies)
	client := &http.Client{
		Jar: jar}
	*/

	req := httplib.Post(e.POST_GROUP_CONTACT_URL + t.GetURLParams(urlMap))
	for _, v := range loginMap.Cookies {
		req.SetCookie(v)
	}

	type userReq struct {
		UserName        string
		EncryChatRoomId string
	}

	type params struct {
		BaseRequest m.BaseRequest
		Count       int
		List        []userReq `json:"List"`
	}

	ur := []userReq{}
	for _, v := range userList {
		ur = append(ur, userReq{UserName: v.UserName})
	}

	p := params{
		BaseRequest: loginMap.BaseRequest,
		Count:       len(userList),
		List:        ur,
	}

	reqStr, _ := json.Marshal(p)
	logs.Info("获得群联系人，请求主体：", reqStr)
	req.Body(reqStr)

	resBytes, err := req.Bytes()
	if err != nil {
		logs.Error(err)
		return
	}

	logs.Info("接收群数据：", string(resBytes[:]))
	userList2 := &m.GroupUser{}
	json.Unmarshal(resBytes, userList2)

	for _, v := range userList2.MemberList {
		resUserList[v.UserName] = v
	}

	return
}
